import { Body, ClassSerializerInterceptor, Controller, HttpException, HttpStatus, Post, UseInterceptors } from '@nestjs/common';
import { AuthService } from './auth.service';
import { SigninUserDto } from './dto/signin-user.dto';
import { CreateUserPipe } from './pipes/create-user.pipe';
import { JwtService } from '@nestjs/jwt';
import { Serialize } from '@/common/decorators/Serialize.decorator';

@Controller('auth')
export class AuthController {

    constructor(private readonly authService: AuthService, private jwt: JwtService) { }

    @Post('/signin')
    sigin(@Body() dto: SigninUserDto) {             // 使用DTO来验证请求体
        const { username, password } = dto
        if (!username || !password) {
            throw new HttpException('用户名或密码不能为空', HttpStatus.BAD_REQUEST)
        }

        const user = this.authService.signin(username, password)

        // return this.authService.signin(username, password)
        return this.jwt.signAsync({ username: user[0].username })     // 返回一个JWT令牌而不是用户信息
    }

    @Post('/signup')
    // @UseInterceptors(ClassSerializerInterceptor)
    @Serialize(SigninUserDto, false)
    async signup(@Body(CreateUserPipe) dto: SigninUserDto) {      // 使用自定义管道来验证请求体
        console.log(dto);
        const { username, password } = dto
        if (!username || !password) {
            throw new HttpException('用户名或密码不能为空', HttpStatus.BAD_REQUEST)
        }

        const user = await this.authService.signup(username, password)
        user.test = {
            roles: [1,2,3],
            date: '2025-10-10'
        }
        return user
    }
}
